package br.com.searchpeople.activity;



import java.io.IOException;
import java.util.concurrent.ExecutionException;

import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import com.savagelook.android.UrlJsonAsyncTask;

import br.com.searchpeople.R;
import br.com.searchpeople.asynctask.LoginTask;
import br.com.searchpeople.database.SingletonAccountBD;
import br.com.searchpeople.model.UserModel;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity {
	//private final static String ENDPOINT_URL = "http://10.5.18.163:3000/api/v1/sessions.json";
	//private final static String ENDPOINT_URL = "http://10.0.2.2:3000/api/v1/sessions.json";
	private final static String ENDPOINT_URL = "http://192.168.1.103:3000/api/v1/sessions.json";
	
	private String user_login;
	private String user_password;
	private Button button_login;
	private TextView registerScreen;
	private String flagNickname;
	private String flagLogin;
	private int flagUserId;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		button_login = (Button) findViewById(R.id.button_login_login);
		button_login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				user_login = ((EditText) findViewById(R.id.edittext_login_user)).getText().toString();
				user_password = ((EditText) findViewById(R.id.edittext_login_password)).getText().toString();
				
				if (user_login.length() > 0 || user_password.length() > 0) {
					
					LoginTask loginTask = new LoginTask(LoginActivity.this, user_login, user_password);
					loginTask.setMessageLoading("Conectando...");
					try {
						JSONObject json = loginTask.execute(ENDPOINT_URL).get();
						if (!json.getBoolean("success")) {
							createSpecificNotificationToast("Tentando Fazer conexão OFFLINE",1);
							if (SingletonAccountBD.getInstance().isAccount(LoginActivity.this, user_login, user_password)) {
								startActivity(new Intent(getApplicationContext(),
										TimelineActivity.class));
								finish();
								flagLogin = user_login;
								flagUserId = (SingletonAccountBD.getInstance().getActualAccount(LoginActivity.this, user_login)).getId();
								String name = SingletonAccountBD.getInstance().getAccountNickname(LoginActivity.this, user_login);
								createSpecificNotificationToast("Bem Vindo " + name, 0);
							} else {
								createSpecificNotificationToast("Usuário e/ou senha inválidos. Tente novamente!",0);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					createSpecificNotificationToast("Preencha todos os campos",0);
				}
			}
		});
		
		// register
		
		registerScreen = (TextView) findViewById(R.id.link_to_signup);
		
		registerScreen.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isNetworkAvailable()) {
				Intent i = new Intent(getApplicationContext(), SignUpActivity.class);
				startActivity(i);
				} else {
					createSpecificNotificationToast("Por Favor conecte-se a Internet",0);
				}
			}
		});
		

	}
	
	@Override
	protected void onStop() {
		super.onStop();
		
		SharedPreferences settings = getSharedPreferences("general",Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		
		try {
			editor.putString("login", flagLogin);
			editor.putInt("user_id", flagUserId);
//			editor.putString("nickname", flagNickname);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			editor.commit();
		}	
	}
	
	private void createSpecificNotificationToast(String arg0, int type) {
		Context context = getApplicationContext();
		CharSequence text = arg0;
		int duration = Toast.LENGTH_SHORT;
		if (type == 1) {
			duration = Toast.LENGTH_LONG;
		}
		Toast toast = Toast.makeText(context, text, duration);
		toast.show();
	}
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}
	
}
